package com.ustze.ocr.type.tencent.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64;
import com.google.common.collect.Maps;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.RecognizeTableAccurateOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.RecognizeTableAccurateOCRResponse;
import com.ustze.ocr.domain.vo.DispatchDetailVo;
import com.ustze.ocr.ocrtype.enums.OcrType;
import com.ustze.ocr.ocrtype.request.OcrRequest;
import com.ustze.ocr.type.tencent.utils.TencentOcrUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class TencentOcrService implements OcrRequest {

    private final TencentOcrUtils tencentOcrUtils;

    @Override
    public Map<String, Object> ocrTable(MultipartFile file) {
        OcrClient client = tencentOcrUtils.createClient();
        try {
            // 实例化一个请求对象,每个接口都会对应一个request对象
            RecognizeTableAccurateOCRRequest req = new RecognizeTableAccurateOCRRequest();
            try {
                String encode = Base64.encode(file.getInputStream());
                req.setImageBase64(encode);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            // 返回的resp是一个RecognizeTableAccurateOCRResponse的实例，与请求对象对应
            RecognizeTableAccurateOCRResponse resp = client.RecognizeTableAccurateOCR(req);
            // 输出json格式的字符串回包
            DispatchDetailVo dispatchDetailVo = TencentOcrUtils.buildVo(resp);
            return BeanUtil.beanToMap(dispatchDetailVo);
        } catch (TencentCloudSDKException e) {
            log.error("腾讯ocr  解析失败 {}", e.toString());
            throw new RuntimeException(e);
        }
    }

    @Override
    public OcrType ocrType() {
        return OcrType.TENCENT;
    }
}
